package com.cyk.fillter;

import com.cyk.config.DefenseConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
public class DefenseAccessFilter implements GlobalFilter, Ordered {
    private static ConcurrentHashMap<String, List<Long>> ipAccessList = new ConcurrentHashMap();

    @Autowired
    private DefenseConfig defenseConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        List<Long> longs = ipAccessList.get(clientIp);
        if (longs == null) {
            longs = new ArrayList<>();
        }

        // 访问限制时长 秒
        Long times = defenseConfig.getTime() * 1000L;
        // 筛选在未超时的浏览记录
        List<Long> countList = longs.stream().filter(t -> (t + times) > new Date().getTime()).collect(Collectors.toList());
        countList.add(new Date().getTime());
        //返回数量统计中
        ipAccessList.put(clientIp, countList);

        //是否超出访问数量
        if (countList.size() > defenseConfig.getCount()) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.SEE_OTHER);
            response.getHeaders().add("content-type", "text/html;charset=UTF-8");
            DataBuffer wrap = response.bufferFactory().wrap("您频繁进⾏注册，请求已被拒绝".getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
